<template>
  <div class="app-container">
    <el-card class="query-card" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input
            v-model="queryParams.templateName"
            placeholder="请输入模板名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="主题" prop="subject">
          <el-input
            v-model="queryParams.subject"
            placeholder="请输入主题"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="发件人" prop="fromEmail">
          <el-select
            v-model="queryParams.fromEmail"
            filterable
            allow-create
            default-first-option
            placeholder="请输入发件人"
            clearable
          >
            <el-option
              v-for="(item, index) in userOptions"
              :key="index"
              :label="item.nickName + '(' + item.email + ')'"
              :value="item.email">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收件人" prop="toEmail">
          <el-select
            v-model="queryParams.toEmail"
            filterable
            allow-create
            default-first-option
            placeholder="请输入收件人"
            clearable
          >
            <el-option
              v-for="(item, index) in userOptions"
              :key="index"
              :label="item.nickName + '(' + item.email + ')'"
              :value="item.email">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="抄送人" prop="ccEmail">
          <el-select
            v-model="queryParams.ccEmail"
            filterable
            allow-create
            default-first-option
            placeholder="请输入抄送人"
            clearable
          >
            <el-option
              v-for="(item, index) in userOptions"
              :key="index"
              :label="item.nickName + '(' + item.email + ')'"
              :value="item.email">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['message:emailTemplate:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['message:emailTemplate:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['message:emailTemplate:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['message:emailTemplate:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <vxe-table
        :loading="loading"
        resizable
        row-key
        ref="tableRef"
        :row-config="{isHover: true}"
        :data="emailTemplateList"
        @checkbox-all="handleSelectionChange"
        @checkbox-change="handleSelectionChange"
        :class="showSearch ? 'table-container' : 'table-container-full'"
      >
        <vxe-column type="checkbox" align="center" min-width="60"/>
        <vxe-column title="模板编码" field="templateCode" align="center" min-width="150" show-overflow/>
        <vxe-column title="模板名称" field="templateName" align="center" min-width="150" show-overflow/>
        <vxe-column title="主题" field="subject" align="center" min-width="150" show-overflowvvv/>
        <vxe-column title="收件人" field="toEmail" align="center" min-width="150" show-overflow/>
        <vxe-column title="抄送人" field="ccEmail" align="center" min-width="150" show-overflow/>
        <vxe-column title="密送人" field="bccEmail" align="center" min-width="150" show-overflow/>
        <vxe-column title="备注" field="remark" align="center" min-width="150" show-overflow/>
        <vxe-column title="操作" align="center" fixed="right" min-width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['message:emailTemplate:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['message:emailTemplate:remove']"
            >删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改邮件模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" append-to-body v-drag-zoom>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板编码" prop="templateCode">
              <el-input v-model="form.templateCode" placeholder="请输入模板编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="主题" prop="subject">
              <el-input v-model="form.subject" placeholder="请输入主题" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="收件人" prop="toEmail">
              <el-select
                v-model="form.toEmail"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入收件人"
                clearable
              >
                <el-option
                  v-for="(item, index) in userOptions"
                  :key="index"
                  :label="item.nickName + '(' + item.email + ')'"
                  :value="item.email">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="抄送人" prop="ccEmail">
              <el-select
                v-model="form.ccEmail"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入抄送人"
                clearable
              >
                <el-option
                  v-for="(item, index) in userOptions"
                  :key="index"
                  :label="item.nickName + '(' + item.email + ')'"
                  :value="item.email">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="密送人" prop="bccEmail">
              <el-select
                v-model="form.bccEmail"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入密送人"
                clearable
              >
                <el-option
                  v-for="(item, index) in userOptions"
                  :key="index"
                  :label="item.nickName + '(' + item.email + ')'"
                  :value="item.email">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容">
              <TinyMceEditor v-model="form.content"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件" prop="attachUrlList">
              <file-upload :visible.sync="open" @setFileUrl="setFileUrl" :limit="20" :file-size="35" :dv-multi-file="true"
                           file-path="/blog/email-attach" :value="form.attachUrlList"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEmailTemplate, getEmailTemplate, delEmailTemplate, addEmailTemplate, updateEmailTemplate } from "@/api/message/emailTemplate";
import TinyMceEditor from '@/components/Tinymce/TinyMceEditor.vue'
import { queryUserEmailOptions } from '@/api/system/user'

export default {
  name: "EmailTemplate",
  components: { TinyMceEditor },
  dicts: ['sys_user_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 邮件模板表格数据
      emailTemplateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null,
        fromEmail: null,
        subject: null,
        toEmail: null,
        ccEmail: null,
      },
      // 用户下拉列表
      userOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.queryUserEmailOptions();
  },
  methods: {
    /** 查询邮件模板列表 */
    getList() {
      this.loading = true;
      listEmailTemplate(this.queryParams).then(response => {
        this.emailTemplateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询用户列表 */
    queryUserEmailOptions() {
      queryUserEmailOptions().then(res => {
        this.userOptions = res.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        templateCode: null,
        templateName: null,
        fromEmail: null,
        subject: null,
        content: null,
        toEmail: null,
        ccEmail: null,
        bccEmail: null,
        attachUrl: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        remark: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(row) {
      this.ids = row.records.map(item => item.id)
      this.single = row.records.length!==1
      this.multiple = !row.records.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加邮件模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEmailTemplate(id).then(response => {
        this.form = response.data;
        if (![null, '', undefined].includes(this.form.toEmail)) {
          this.form.toEmail = this.form.toEmail.split(';');
        }
        if (![null, '', undefined].includes(this.form.ccEmail)) {
          this.form.ccEmail = this.form.ccEmail.split(';');
        }
        if (![null, '', undefined].includes(this.form.bccEmail)) {
          this.form.bccEmail = this.form.bccEmail.split(';');
        }
        if (![null, '', undefined].includes(this.form.attachUrl)) {
          this.form.attachUrlList = this.form.attachUrl.split(';');
        }
        this.open = true;
        this.title = "修改邮件模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.form));
          if (![null, '', undefined].includes(data.toEmail)) {
            data.toEmail = data.toEmail.join(';');
          }
          if (![null, '', undefined].includes(data.ccEmail)) {
            data.ccEmail = data.ccEmail.join(';');
          }
          if (![null, '', undefined].includes(data.bccEmail)) {
            data.bccEmail = data.bccEmail.join(';');
          }
          if ((typeof data.attachUrlList) === 'string') {
            data['attachUrlList'] = data.attachUrlList.split(',');
          }
          if (data.id != null) {
            updateEmailTemplate(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEmailTemplate(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除邮件模板编号为"' + ids + '"的数据项？').then(function() {
        return delEmailTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('message/emailTemplate/export', {
        ...this.queryParams
      }, `emailTemplate_${new Date().getTime()}.xlsx`)
    },
    /** 回写附件数据 */
    setFileUrl(url) {
      this.$set(this.form, 'attachUrlList', url);
      this.showFileSelect = false;
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .table-container {
  .vxe-table {
    height: calc(100vh - 364.5px);
  }
  .vxe-table--body-wrapper {
    height: calc(100vh - 408.5px);
  }
  .fixed-left--wrapper,
  .fixed-right--wrapper {
    height: calc(100vh - 417.5px);
  }
}
</style>
